import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from "../views/Home";
import Index from "../views/Index";

import axios from "../axios";
import store from "../store";

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
      {
        path: '/index',
        name: 'Index',
        component: Index
      },
      {
        path: '/userCenter',
        name: 'UserCenter',
        component: () => import('../views/UserCenter.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  }
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});

router.beforeEach((to, from, next) => {
  // 是否有token
  let token = localStorage.getItem('token');
  // 是否有路由
  let hasRoute = store.state.tabs.hasRoute;
  if (to.path == '/login') {
    next();
  } else if (!token) {
    next({path: '/login'});
  } else if (token && !hasRoute) {
    axios.get('/sys/menu/nav',{
      headers: {
        Authorization: localStorage.getItem('token')
      }
    }).then(res => {
      // 拿到tabList
      store.commit('SET_TABLIST',res.data.data.nav);
      // 拿到用户的权限
      store.commit('SET_PERMS',res.data.data.perms);
      // 动态绑定路由
      let currentRouter = router.options.routes;
      let newRouter = [];
      // 父级循环
      console.log(currentRouter)
      res.data.data.nav.forEach(tab =>{
        // 有子级才循环绑定子级标签路由
        if (tab.children) {
          tab.children.forEach(child => {
            // 转成路由
            let item = tabToRouter(child);
            // 不为空添加
            if (item) newRouter.push(item);
          });
        }
      });
      hasRoute = true;
      store.commit('SET_HASROUTE', hasRoute);
      currentRouter[0].children = [...currentRouter[0].children,...newRouter];
      router.addRoutes(currentRouter);
      // console.log(router.options.routes[0].children)
    });
  }
  next();
});

// 导航转成路由
const tabToRouter = (child) => {
  if (!child.component) return null;
  let item = {
    path: child.path,
    name: child.name,
    meta: {
      icon: child.icon,
      title: child.title
    },
    component: () => import('@/components/'+child.component+'.vue')
  };
  return item;
};

export default router;
